var _CONFIG = {
    JQXGRID: '#jqx_grid_view',
    CATEGORYS:null,
    CATEFILLTER:'',
    cBINDING_URI: base_url + 'so/category/gets',
    tBINDING_URI: base_url + 'so/news/binding/',
    BINDING_URI: base_url + 'so/news/binding/',
    EDITPANEL_URI:base_url + 'so/news/editpanel/',
    COMMIT_URI:base_url + 'so/excution/commit/news/news/',
    DELETE_URI:base_url + 'so/excution/delete/news/news/'
};
var _SO = (function() {
    var datafields = [
        {name: 'Id', type: 'int'},
        {name: 'Thumb'},
        {name: 'Title'},
        {name: 'CategoryId'},
        {name: 'Position',type: 'int'},
        {name: 'Active',type: 'bool'},
        {name: 'Insert', type: 'date'},
        {name: 'Update', type: 'date'},
        {name: 'StartDate', type: 'date'},
    ];
    var columns = [
        {
            text: '', dataField: 'Id', width: 60, filterable: false, sortable: false,editable: false,
            cellsrenderer: function (row, columnfield, value, defaulthtml, columnproperties) {
                var str = "";
                if (value && value > 0) {
                    try {
                        //value = $.parseJSON(value);
                        str += "\
                            <span style='margin: 4px 4px 4px 12px; float: left;' class=\"icon-pencil\" onclick=\"_SO.onEditItem(" + value + ");\"  title='Edit:" + value + "'></span>\
                        ";
                        str += "\
                            <span style='margin: 4px; float: left;' class='icon-trash' onclick=\"_SO.onDeleteItem(" + value + ");\" title='Delete:" + value + "'></span>\
                        ";
                    } catch (e) {
                    }
                }

                return str;
            }
        },
        {text: 'Hình ảnh'     , dataField: 'Thumb'   ,width:60,filterable:false ,sortable: false,
            cellsrenderer: function (row, columnfield, value, defaulthtml, columnproperties) {
                if(value==undefined || value=='')
                    return '';
                else{
                    
                    return '<img onError="this.src = \'/libraries/images/22/picture.png\'" class="cellthumb" height="32" src="' + getImageSrc(value) + '"/>';
                }
            }
        },
        {
            text: 'Tiêu đề'       , dataField: 'Title'     ,
            validation:function (cell, value) {
                if (value =="") {
                    return { result: false, message: "Title should be non empty." };
                }
                return true;
            }
        },
        {
            text: 'Danh mục'    , dataField: 'CategoryId' , 
            filterable:false,columntype: 'template',
            cellsrenderer: function (row, columnfield, value, defaulthtml, columnproperties) {
                var str = '<div style="overflow: hidden; text-overflow: ellipsis; padding-bottom: 4px; text-align: left; margin-right: 2px; margin-left: 4px; padding-top: 4px;">';
                try{
                    var avalue = value.split(',');
                    for (var i = 0; i < avalue.length; i++) {
                        var display = avalue[i];
                        try{
                            for(var j=0;j<_CONFIG.CATEGORYS.length;j++){
                                if(avalue[i]==_CONFIG.CATEGORYS[j].Id){
                                    display = _CONFIG.CATEGORYS[j].Title;
                                    display+='<sup>('+_CONFIG.CATEGORYS[j].Type+')</sup>';
                                    
                                    break;
                                }
                            }
                        }catch(e){
                            
                        }
                        str += "<span class='label label-info' >" + display + "</span>";
                        //str += display;
                        if(i+1 < avalue.length){
                            str+='&nbsp;';
                        }
                    }
                }catch(e){str += "<span class='label label-info' >" + value + "</span>";}
                str+='</div>';
                return str;
            },
            createeditor: function(row, cellvalue, editor, cellText, width, height) {
                // construct the editor. 
                editor.jqxDropDownList({
                    checkboxes: true,
                    source: _CONFIG.CATEGORYS, displayMember: "Title", valueMember: "Id",
                    width: width, height: height, theme: theme,
                    selectionRenderer: function() {
                        return "Please Choose:";
                    }
                });
            },
            initeditor: function(row, cellvalue, editor, celltext, pressedkey) {
                // set the editor's current value. The callback is called each time the editor is displayed.
                //editor.jqxDropDownList('setContent', celltext); 
                var items = editor.jqxDropDownList('getItems');
                editor.jqxDropDownList('uncheckAll');
                var values = cellvalue.split(/,\s*/);
                for (var j = 0; j < values.length; j++) {
                    for (var i = 0; i < items.length; i++) {
                        if (items[i].value === values[j]) {
                            editor.jqxDropDownList('checkItem', items[i]);
                        }
                    }
                }
            },
            geteditorvalue: function(row, cellvalue, editor) {
                // return the editor's value.
                return editor.val();
            }
        },
        {
            text: 'Thứ tự'       , dataField: 'Position'    ,
            width: 80, filterable: false, cellsalign: 'right', 
            columntype: 'numberinput', filtertype: 'number',
            validation:function (cell, value) {
                if (value < 0 || value > 99) {
                    return { result: false, message: "Position should be in the 0-99 interval." };
                }
                return true;
            }},
        {text: 'Trạng thái'    , dataField: 'Active' , width: 80, filterable: true, columntype: 'checkbox', threestatecheckbox: false, filtertype: 'bool' },
        {text: 'Created'        , dataField: 'Insert'      , width: 120, filterable: true,filtertype: 'date', cellsformat: 'yyyy-MM-dd HH:mm:ss', editable: false},
        {
            text: 'Ngày bắt đầu'      , dataField: 'StartDate'    , 
            width: 120, filterable: true,filtertype: 'date', cellsformat: 'yyyy-MM-dd', editable: true,
            columntype: 'datetimeinput',
            geteditorvalue: function(row, cellvalue, editor) {
                // return the editor's value.
                return editor.jqxDateTimeInput('getText');
            }
            
        }
    ];
    var oTable;
    var that = this;
    return {
        onCommit: function(Params, Id,callback) {
            /* Commit data lên vào DB, Id>0 là Update, Id=0 hoặc ko có là Insert */
            backend({
                url: _CONFIG.COMMIT_URI,
                data: {
                    Id: Id,
                    Params: Params
                },
                callback: function(rsdata) {
                    if (rsdata.result < 0) {
                        $.jGrowl(rsdata.message, {sticky: true, theme: 'growl-error', header: 'Error!'});
                    } else {
                        $.jGrowl(rsdata.message);
                        if (typeof callback == 'function') {
                            callback();
                        }
                    }
                }
            }).call();
        },
        creategrid  :   function(){
            var source = {
                datatype: "json", type: "POST",
                datafields: datafields,
                url: _CONFIG.BINDING_URI,
                filter: function() {
                    $(_CONFIG.JQXGRID).jqxGrid('updatebounddata', 'filter');
                },
                sort: function() {
                    $(_CONFIG.JQXGRID).jqxGrid('updatebounddata');
                },
                root: 'rows',
                beforeprocessing: function(data) {
                    
                }
            };
            var dataAdapter = new $.jqx.dataAdapter(source, {
                loadError: function(xhr, status, error) {
                    bckdialog({type: 'error'}).open("<b>Status</b>:" + xhr.status + "<br/><b>ThrownError</b>:" + error + "<br/>", 'Error Message!');
                }
            });
            $(_CONFIG.JQXGRID).jqxGrid({
                width: '100%', //autoheight:true,
                //height: '100%',
                source: dataAdapter,
                theme: theme, sortable: true,
                filterable: true,
                autoshowfiltericon: true,
                showfilterrow: true,
                editable: true,
                //rowsheight:34,
                showemptyrow: true,
                columns: columns,
                selectionmode: 'singlecell',
                editmode: 'dblclick',
                virtualmode: true,
                //groupable: true,
                rendergridrows: function(){ return dataAdapter.records; },
                pageable: true,
                pagesize: 100,
                pagesizeoptions: ['100', '200', '500', '1000'],
                ready: function() {
                    var $refresh = $('<div type="button"  title="Tải lại" style="margin-left: 0px;padding:0 4px; float: left; cursor: pointer;height:15px;"><img src="/libraries/images/16/view_refresh.png"/></div>');
                    var $option = $('<div type="button"  title="Tùy chỉnh" style="margin-left: 0px;padding:0 4px; float: left; cursor: pointer;height:15px;"><img src="/libraries/images/16/option.gif"/></div>');
                    var $add = $('<div type="button"  title="Thêm mới" style="margin-left: 4px;padding:0 4px; float: left; cursor: pointer;height:15px;"><img src="/libraries/images/16/add_1.png"/></div>');
                    $refresh.click(function(){
                        _SO.onRefresh();
                    });
                    $add.click(function(){
                        _SO.onAddItem();
                    });
                    $option.prependTo($(_CONFIG.JQXGRID+' .jqx-grid-pager>div'));
                    $refresh.prependTo($(_CONFIG.JQXGRID+' .jqx-grid-pager>div'));
                    $add.prependTo($(_CONFIG.JQXGRID+' .jqx-grid-pager>div'));
                    
                },
				handlekeyboardnavigation: function(event)
                {
                    var key = event.charCode ? event.charCode : event.keyCode ? event.keyCode : 0;
                    if (key == 27) {
                        that.cancel=true;
                    }
                },

            }).bind('cellbeginedit', function (event) {
                that.cancel=false;
            }).bind('cellendedit', function (event) {
                /* Lưu dữ liệu khi chỉnh sửa trên lưới */
                if(that.cancel)return;
                /* Lưu dữ liệu khi chỉnh sửa trên lưới */
                try{
                    var args = event.args;
                    var column = args.datafield, _row = args.rowindex, _value = args.value;
                    var _data = $(_CONFIG.JQXGRID).jqxGrid('getrowdata', _row);
                    var _id = _data.Id;
                    if (_id == undefined || _id == "") {
                        return;
                    }
                    switch (column) {
                        case 'Title':
                            if (_value != _data.Title && _value!='')
                                _SO.onCommit({Title: _value}, _id);
                            break;
                        case 'CategoryId':
                            if (_value != _data.CategoryId)
                                _SO.onCommit({CategoryId: _value}, _id);
                            break;
                        case 'Position':
                            if (_value != _data.Position)
                                _SO.onCommit({Position: _value}, _id);
                            break;
                        case 'Active':
                            if (_value)
                                _SO.onCommit({Active: 'true'}, _id);
                            else
                                _SO.onCommit({Active: 'false'}, _id);
                            break;
                        case 'StartDate':
                            if (_value != _data.StartDate)
                                _SO.onCommit({StartDate: _value}, _id);
                            break;
                        default:
                            $.jGrowl("Chưa mở tính năng sửa trực tiếp cột này", {sticky: true, theme: 'growl-error', header: 'Error!'});
                    }
                } catch (e) {
                    $.jGrowl(e.message, {sticky: true, theme: 'growl-error', header: 'Error!'});
                    //bckdialog({type:'error'}).open(e.message);
                }
            });
        },
        createtable :   function(){
            $('#viewport').hide();
            return;
             oTable = $('#data_table').dataTable({
                aaSorting: [],
                aoColumns: [
                    {
                        mData: "Id",sWidth: "58px",//sClass:'',
                        mRender: function ( value, type, datarow ) {
                            var str = "";
                            str += '<span class="icon-pencil" title="Edit:'+value+'" style="padding-right:12px" onclick="_SO.onEditItem(' + value + ');"></span>';
                            str += '<span class="icon-trash" title="Delete:'+value+'" style="padding-right:12px" onclick="_SO.onDeleteItem(' + value + ');"></span>';

                            return str;
                        }
                    },
                    {
                        mData: "Thumb",sWidth: "58px",
                        mRender: function ( value, type, datarow ) {
                            var str = "";
                            if(value!==undefined && value !==null  && value!=='')
                                str += '<img src="' + value + '" style="height:24px"/>';
                            return str;
                        }
                    },
                    {
                        mData: "Title"
                    },
                    {
                        mData: "CategoryId",
                        mRender: function ( value, type, datarow ) {
                            var str='';
                            try{
                                var avalue = value.split(',');
                                for (var i = 0; i < avalue.length; i++) {
                                    var display = avalue[i];
                                    try{
                                        for(var j=0;j<_CONFIG.CATEGORYS.length;j++){
                                            if(avalue[i]==_CONFIG.CATEGORYS[j].Id){
                                                display = _CONFIG.CATEGORYS[j].Title;
                                                display+='<sup>('+_CONFIG.CATEGORYS[j].Type+')</sup>';
                                                break;
                                            }
                                        }
                                    }catch(e){}
                                    str += display;
                                    if(i+1 < avalue.length){
                                        str+=', ';
                                    }
                                }
                            }catch(e){str=value}
                            return str;
                        }
                    },
                    {mData: "Position"},
                    {
                        mData: "Active",sClass:'center',sWidth: "58px",
                        mRender: function ( value, type, datarow ) {
                            var str = "";
                            if(value==='true')
                                str+='<input type="checkbox" onclick="_SO.onStatusChange(this,'+datarow.Id+');" checked=1/>';
                            else
                                str+='<input type="checkbox" onclick="_SO.onStatusChange(this,'+datarow.Id+');"/>';
                            return str;
                        }
                    },
                    {mData: "Insert"},
                    {mData: "Update"}
                ],
                sServerMethod: "POST",
                iDisplayLength: 10,
                bProcessing: true,
                bServerSide: true,
                //bPaginate: false,
                //bSortable:false,
                //bFilter :false,
                sAjaxSource: _CONFIG.tBINDING_URI,
                bJQueryUI: false,
                bAutoWidth: false,
                sPaginationType: "full_numbers",
                //sDom": '<"datatable-header"fl>t<"datatable-footer"ip>',
                oLanguage: {
                    sSearch: "<span>Filter records:</span> _INPUT_",
                    sLengthMenu: "<span>Show entries:</span> _MENU_",
                    oPaginate: {"sFirst": "First", "sLast": "Last", "sNext": ">", "sPrevious": "<"}
                }
            });
            oTable.fnSetFilteringDelay(2000);
        },
        onInit  :   function(){
            backend({
                url         :   _CONFIG.cBINDING_URI,
                data        :   {
                },
                callback    :   function(rsdata){
                    if(rsdata.result<0){
                        bckdialog({type:'error'}).open(rsdata.message);
                    }else{
                        _CONFIG.CATEGORYS=rsdata.data;
                        for(var i=0;i<_CONFIG.CATEGORYS.length;i++){
                            _CONFIG.CATEGORYS[i].group=_CONFIG.CATEGORYS[i].Type;
                            _CONFIG.CATEGORYS[i].html=_CONFIG.CATEGORYS[i].Display;
                        }
                        _SO.createtable();
                        _SO.creategrid();
                    }
                }
            }).call();
            
        },
        onAddItem:function(){
            this.onEditItem(0);
        },
        onEditItem:function(Id){
            if (PENDING)
                return false;
            $('#viewport').hide();
            $('#jqxviewport').hide();
            $('#edit_panel_insite').show().html('<div class="base_loading" style="display: block;height: 60px"></div>');
            backend({
                url         :   _CONFIG.EDITPANEL_URI+_CONFIG.TYPE,
                data        :   {
                    Id  :   Id
                },
                callback    :   function(rsdata){
                    if(rsdata.result<0){
                        $('#edit_panel_insite').html('<span style="color:red">'+rsdata.message+'</span>');
                        
                    }else{
                        $('#edit_panel_insite').html(rsdata.htmlreponse);
                        $('#Active').select2({minimumResultsForSearch: -1});
//                        islc({
//                            element:'#edit_panel_insite .select',
//                            multiple:true,
//                            selectedList:1,
//                            height:240,
//                        });
                        $("#jqxComboBox").jqxDropDownList({
                            checkboxes: true,theme:theme,
                            source: _CONFIG.CATEGORYS, displayMember: "Title", valueMember: "Id",
                            //multiSelect: true, 
                            width: '100%', height: 28
                        });//.jqxDropDownList('checkIndex', 1);    
                        var items = $("#jqxComboBox").jqxDropDownList('getItems'); 
                        var _index=0;
                        try{
                            for(var i=0;i<items.length;i++){
                                if(items[i].isGroup!==true){
                                    if($('#CategoryId').val().indexOf(items[i].value)>=0){
                                        $("#jqxComboBox").jqxDropDownList('checkIndex', _index);
                                    }
                                    _index++;
                                }
                            }
                        }catch(e){
                            bckdialog({type:'error'}).open(e.message);
                        }
                        $("#Related").tokenInput("/so/news/tokeninput",{
                            propertyToSearch:'Title',
                            //tokenValue:'Id',
                            preventDuplicates: true,
                            //queryParam:'sSearch'
                            prePopulate:rsdata.related,
//                            onResult: function (results) {
//                                $.each(results, function (index, value) {
//                                    value.id = value.Id;
//                                });
//                                return results;
//                            }
                        });
                        addEditorFeature('Content');
                        $( ".datepicker" ).datepicker({
				defaultDate: +7,
                                showOtherMonths:true,
                                autoSize: true,
                                //appendText: '(dd-mm-yyyy)',
                                dateFormat: 'yy-mm-dd'
                        });
                    }
                }
            }).call();
        },
        onSave:function(){
            try{
                if( $('#_form_edit_panel').validationEngine('validate') === false)return false;
                var Params=$('#_form_edit_panel').serializeObject();
                Params.Content = CKEDITOR.instances['Content'].getData();
                Params.CategoryId=$("#jqxComboBox").jqxDropDownList('val');
                delete Params.jqxComboBox;
                if(Params.StartDate==="")delete Params.StartDate;
                if(Params.EndDate==="")delete Params.EndDate;
                this.onCommit(Params,$('#Id').val(),function(){
                    _SO.onRefresh();
                    _SO.onCancel();
                });
            }catch(e){
                bckdialog({type:'error'}).open(e.message);
            }
            return false;
        },
        onCancel:function(){
             //$('#viewport').show();
             $('#jqxviewport').show();
            $('#edit_panel_insite').hide();
        },
        onDeleteItem:function(Id){
            backend_delete(_CONFIG.DELETE_URI,Id,function(){
                _SO.onRefresh();
            });
        },
        onRefresh:function(){
            //oTable.fnDraw(false);
            $(_CONFIG.JQXGRID).jqxGrid('updatebounddata');
        },
        onFillter:function(v){
            oTable.fnFilter(v, 2);
        },
        onStatusChange:function(that,Id){
            var _status = $(that).is(':checked')?'true':'false';
            new backend({
                url         :   _CONFIG.COMMIT_URI,
                data        :   {
                    Params  :   {
                        staf_status:_status
                    },
                    Id      :   Id
                },
                callback    :   function(rsdata){
                    if(rsdata.result<0){
                        bckdialog({type:'error'}).open(rsdata.message);
                    }
                }
            }).call();
        },
        onChangeSource:function(type){
            _CONFIG.TYPE=type;
            oTable.fnDestroy();
            this.createtable();
            //oTable.fnReloadAjax(_CONFIG.tBINDING_URI+_CONFIG.TYPE);
        }
    };
}());

$(document).ready(function(){
    _SO.onInit();
    
    //$('.select').select2();
});
